package com.trsj.lnsj.service.imp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.trsj.lnsj.common.DataResponse;
import com.trsj.lnsj.common.MsgStatus;
import com.trsj.lnsj.entity.EaseGroupDTO;
import com.trsj.lnsj.entity.EaseGroupRepo;
import com.trsj.lnsj.util.HttpRequestUtil;
import com.trsj.lnsj.util.ResponseHelper;
import groovy.util.logging.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 
 * <p>
 * Title: EaseGroupService
 * </p>
 * 
 * <p>
 * Description:
 * </p>
 * 
 * <p>
 * Copyright: Copyright (c) 2018
 * </p>
 * 
 * <p>
 * Company: 七色环
 * </p>
 * 
 * @author jiaxb
 * 
 * @date 2019年3月30日
 * 
 * @version 1.0
 * 
 */
@Slf4j
@Service
public class EaseGroupService {
    private Logger  logger = LoggerFactory.getLogger(EaseGroupService.class);
    @Value("${EASE.URI}")
    private String easeUri;
    @Value("${EASE.ORG_NAME}")
    private String easeOrgName;
    @Value("${EASE.APP_NAME}")
    private String easeAppName;
    @Value("${EASE.GRANT_TYPE}")
    private String easeGrantType;
    @Value("${EASE.CLIENT_ID}")
    private String easeClientId;
    @Value("${EASE.CLIENT_SECRET}")
    private String easeClientSecret;
    @Autowired
    private RedisService redisService;
    @Autowired
    private EaseGroupRepo easeGroupRepo;

    /**
     * 获取App中所有的群组（可分页）
     * @return
     */
    public DataResponse getAppAllGroups(String limit, String cursor) {
        String url = easeUri + "/" + easeOrgName + "/" + easeAppName + "/chatgroups";
        String param = "limit="+limit;
        if(StringUtils.isNotBlank(cursor)){
            param += "&cursor="+cursor;
        }
        String token = getEaseToken();
        String result = HttpRequestUtil.sendGet(url, param, token);
        JSONObject json = JSONObject.parseObject(result);
        JSONArray groupJson = json.getJSONArray("data");
        return ResponseHelper.getSuccessResponse(groupJson);
    }

    /**
     * 获取环信token接口
     * @return
     */
    public String getEaseToken() {
        String url = easeUri+"/"+easeOrgName+"/"+easeAppName+"/token";
        String ds = "{\n" +
                "  \"grant_type\": \""+easeGrantType+"\",\n" +
                "  \"client_id\": \""+easeClientId+"\",\n" +
                "  \"client_secret\": \""+easeClientSecret+"\"\n" +
                "}";
        String easeToken = redisService.get("easeToken");
        if (StringUtils.isBlank(easeToken)) {
            String result = HttpRequestUtil.sendPost(url,ds, null);
            JSONObject json = JSON.parseObject(result);
            easeToken = "Bearer " + json.getString("access_token");
            long expiresMillis = json.getLongValue("expires_in");
            redisService.set("easeToken",easeToken,expiresMillis);
        }
        return easeToken;
    }

    public DataResponse createSingleEaseGroup(String groupname, String desc, boolean isPublic, int maxusers, boolean approval, String owner) {
        String url = easeUri + "/" + easeOrgName + "/" + easeAppName + "/chatgroups";
        String content = "{\n" +
                "  \"groupname\": \"" + groupname + "\",\n" +
                "  \"desc\": \"" + desc + "\",\n" +
                "  \"public\":" + isPublic + ",\n" +
                "  \"maxusers\":" + maxusers + ",\n" +
                "  \"approval\":" + approval + ",\n" +
                "  \"owner\": \"" + owner + "\",\n" +
                "}";
        String result = HttpRequestUtil.sendPost(url, content, getEaseToken());
        EaseGroupDTO easeGroup = new EaseGroupDTO();
        easeGroup.setGroupname(groupname);
        easeGroup.setOwner(owner);
        easeGroup.setIsPublic(isPublic);
        easeGroup.setDesc(desc);
        easeGroup.setMaxusers(maxusers);
        easeGroup.setApproval(approval);
        easeGroup.setCreateTime(new Date());
        easeGroup.setUpdateTime(new Date());
        easeGroupRepo.saveAndFlush(easeGroup);
        logger.info("创建环信聊天群组");
        return ResponseHelper.getSuccessResponse(result);
    }

    /**
     * 移除指定群组中黑名单中成员
     *
     * @param groupId       群组ID
     * @param usernames     用户ID，多个用户用','分割
     * @return
     */
    public DataResponse deleteBlocksUsers(String groupId, String usernames) {
        //http://{{hx_url}}/{{org_name}}/{{app_name}}/chatgroups/78363555332097/blocks/users/ggjj,56rr
        String url = easeUri + "/" + easeOrgName + "/" + easeAppName + "/chatgroups/" + groupId + "/blocks/users/" + usernames;
        String token = getEaseToken();
        String result = HttpRequestUtil.doDelete(url, token);
        JSONObject json = JSONObject.parseObject(result);
        if(json.containsKey("data")) {
            JSONArray userJson = json.getJSONArray("data");
            return ResponseHelper.getSuccessResponse(userJson);
        } else {
            return  ResponseHelper.getSuccessResponse(json);
        }
    }

    /**
     * 添加用户到指定群组黑名单
     *
     * @param groupId       群组ID
     * @param usernames     用户ID，多个用户","分割
     * @return
     */
    public DataResponse addBlocksUsers(String groupId, String usernames) {
        //http://{{hx_url}}/{{org_name}}/{{app_name}}/chatgroups/78363555332097/blocks/users
        String url = easeUri + "/" + easeOrgName + "/" + easeAppName + "/chatgroups/" + groupId + "/blocks/users";
        String token = getEaseToken();
        String[] usernamesArray = usernames.split(",");
        JSONObject usernameJson = new JSONObject();
        usernameJson.put("usernames",usernamesArray);
        String result = HttpRequestUtil.doPost(url, usernameJson.toJSONString(), token);
        JSONObject json = JSONObject.parseObject(result);
        if(json.containsKey("data")) {
            JSONArray userJson = json.getJSONArray("data");
            return ResponseHelper.getSuccessResponse(userJson);
        } else {
            return  ResponseHelper.getSuccessResponse(json);
        }
    }

    /**
     * 获取群组中所有用户
     *
     * @param groupId
     * @return
     */
    public DataResponse getGroupUsers(String groupId) {
        //http://{{hx_url}}/{{org_name}}/{{app_name}}/chatgroups/78363555332097/users
        String url = easeUri + "/" + easeOrgName + "/" + easeAppName + "/chatgroups/" + groupId + "/users";
        String token = getEaseToken();
        String result = HttpRequestUtil.sendGet(url, null, token);
        JSONObject json = JSONObject.parseObject(result);
        if(json.containsKey("data")) {
            JSONArray userJson = json.getJSONArray("data");
            return ResponseHelper.getSuccessResponse(userJson);
        } else {
            return  ResponseHelper.getSuccessResponse(json);
        }
    }

    /**
     * 删除群组中用户
     *
     * @param groupId
     * @param usernames
     * @return
     */
    public DataResponse deleteGroupUsers(String groupId, String usernames) {
        //http://{{hx_url}}/{{org_name}}/{{app_name}}/chatgroups/78363555332097/users/ggjj,56rr
        String url = easeUri + "/" + easeOrgName + "/" + easeAppName + "/chatgroups/" + groupId + "/users/" + usernames;
        String token = getEaseToken();
        String result = HttpRequestUtil.doDelete(url, token);
        JSONObject json = JSONObject.parseObject(result);
        if(json.containsKey("data")) {
            JSONArray userJson = json.getJSONArray("data");
            return ResponseHelper.getSuccessResponse(userJson);
        } else {
            return  ResponseHelper.getSuccessResponse(json);
        }
    }

    /**
     * 添加群组中用户
     *
     * @param groupId
     * @param username
     * @return
     */
    public DataResponse addGroupUsers(String groupId, String username) {
        //http://{{hx_url}}/{{org_name}}/{{app_name}}/chatgroups/78363555332097/users
        String url = easeUri + "/" + easeOrgName + "/" + easeAppName + "/chatgroups/" + groupId + "/users";
        String token = getEaseToken();
        JSONObject usernameJson = new JSONObject();
        usernameJson.put("usernames",username.split(","));
        String result = HttpRequestUtil.doPost(url, usernameJson.toString(), token);
        JSONObject json = JSONObject.parseObject(result);
        if(json.containsKey("data")) {
            JSONArray userJson = json.getJSONArray("data");
            return ResponseHelper.getSuccessResponse(userJson);
        } else {
            return  ResponseHelper.getSuccessResponse(json);
        }
    }

    /**
     * 群主转让，转让给指定用户
     *
     * @param groupId
     * @param newOwner
     * @return
     */
    public DataResponse transferGroup(String groupId, String newOwner) {
//        http://{{hx_url}}/{{org_name}}/{{app_name}}/chatgroups/78363555332097
        String url = easeUri + "/" + easeOrgName + "/" + easeAppName + "/chatgroups/" + groupId;
        String token = getEaseToken();
        String result = HttpRequestUtil.doPut(url, newOwner, token);
        JSONObject json = JSONObject.parseObject(result);
        if(json.containsKey("data")) {
            JSONArray userJson = json.getJSONArray("data");
            return ResponseHelper.getSuccessResponse(userJson);
        } else {
            return  ResponseHelper.getSuccessResponse(json);
        }
    }

    public DataResponse getGroupsDetail(String groupIds) {
        String url = easeUri + "/" + easeOrgName + "/" + easeAppName + "/chatgroups/" + groupIds;
        String result = HttpRequestUtil.sendGet(url,null, getEaseToken());
        JSONObject json = JSONObject.parseObject(result);
        JSONArray groupJson = json.getJSONArray("data");
        return ResponseHelper.getSuccessResponse(groupJson);
    }

    /**
     * 删除群组
     * @param groupId
     * @return
     */
    public DataResponse deleteGroup(String groupId) {
        String url = easeUri + "/" + easeOrgName + "/" + easeAppName + "/chatgroups/" + groupId;
        try {
            String result = HttpRequestUtil.doDelete(url,getEaseToken());
            return ResponseHelper.getSuccessResponse(result);
        } catch (Exception e) {
            logger.info(e.getMessage());
            return  ResponseHelper.getResponse(MsgStatus.STATUS_FAILED);
        }
    }

    /**
     * 修改群组信息
     * @param groupId
     * @return
     */
    public DataResponse updateGroup(String groupId,String groupName, String description, Integer maxusers) {
        String url = easeUri + "/" + easeOrgName + "/" + easeAppName + "/chatgroups/" + groupId;
        String content = "{\n" +
                "  \"groupname\": \""+groupName+ "\",\n" +
                "  \"description\": \""+description+"\",\n" +
                "  \"maxusers\": "+maxusers+
                "}";
        try {
            String result = HttpRequestUtil.doPut(url,content,getEaseToken());
            return ResponseHelper.getSuccessResponse(result);
        } catch (Exception e) {
            logger.info(e.getMessage());
            return  ResponseHelper.getResponse(MsgStatus.STATUS_FAILED);
        }
    }

    /**
     * 查询群组黑名单
     * @param groupId
     * @return
     */
    public DataResponse queryBlockUsers(String groupId) {
        String url = easeUri + "/" + easeOrgName + "/" + easeAppName + "/chatgroups/" + groupId + "/blocks/users";
        try {
            String result = HttpRequestUtil.sendGet(url, null, getEaseToken());
            return ResponseHelper.getSuccessResponse(result);
        } catch (Exception e) {
            logger.info(e.getMessage());
            return ResponseHelper.getResponse(MsgStatus.STATUS_FAILED);
        }
    }
}
